<script setup lang="ts">
import { reactive, Ref, ref, watch } from 'vue'
import { useRoute } from 'vue-router'
import { findBanner } from '@/service/api/home'
import { findCurrentCategory } from '@/service/api/category'
import { IBanner } from '@/service/api/type/home.type'
import { ICurCategory } from '@/service/api/type/category.type'
import CategoryPanel from './components/category-panel.vue'

const bannerList: Ref<IBanner[]> = ref([])

const getBannerData = async () => {
  const { result } = await findBanner()
  bannerList.value = result
}
getBannerData()

let currentCategory: ICurCategory = reactive({
  id: '',
  name: '',
  picture: '',
  children: []
})

const route = useRoute()
const getCurrentCategoryData = async (id: string) => {
  const { result } = await findCurrentCategory(id)
  Object.assign(currentCategory, result)
}
watch(
  () => route.params.id,
  (id) => {
    const condition =
      id &&
      !route.path.includes('/category/sub') &&
      route.path.includes('/category')
    if (condition) {
      getCurrentCategoryData(id as string)
    }
  },
  {
    immediate: true
  }
)
</script>
<script lang="ts">
export default {
  name: 'TopCategory'
}
</script>

<template>
  <div class="top-category">
    <div class="container">
      <Bread>
        <BreadItem to="/">首页</BreadItem>
        <Transition name="fade-right" mode="out-in">
          <BreadItem :key="currentCategory.id">{{
            currentCategory.name
          }}</BreadItem>
        </Transition>
      </Bread>
      <Carousel :sliders="bannerList" style="height: 500px" />

      <div class="sub-list">
        <h3>全部分类</h3>
        <ul v-if="currentCategory">
          <li v-for="item in currentCategory.children" :key="item.id">
            <a href="javascript:;">
              <img :src="item.picture" />
              <p>{{ item.name }}</p>
            </a>
          </li>
        </ul>
      </div>
      <CategoryPanel
        :sub-category="item"
        v-for="item in currentCategory.children"
        :key="item.id"
      ></CategoryPanel>
    </div>
  </div>
</template>

<style lang="less" scoped>
.top-category {
  h3 {
    font-size: 28px;
    color: #666;
    font-weight: normal;
    text-align: center;
    line-height: 100px;
  }
  .sub-list {
    margin-top: 20px;
    background-color: #fff;
    ul {
      display: flex;
      padding: 0 32px;
      flex-wrap: wrap;
      li {
        width: 168px;
        height: 160px;
        a {
          text-align: center;
          display: block;
          font-size: 16px;
          img {
            width: 100px;
            height: 100px;
          }
          p {
            line-height: 40px;
          }
          &:hover {
            color: @themeColor;
          }
        }
      }
    }
  }
}
</style>
